<template>
  <div class="current-students">
    <GoBack :title="title" />
    <div class="current-students-search">
      <div class="use-btn">
        <div class="collapse-btn" @click="setCollapse">
          <span v-if="isCollapse"
            >展开<el-icon style="margin-left: 10px"
              ><ArrowDown /></el-icon></span
          ><span v-else
            >收起<el-icon style="margin-left: 10px"><ArrowUp /></el-icon
          ></span>
        </div>
      </div>
      <el-form :model="form" ref="ruleFormRef" label-width="auto">
        <el-row :gutter="0" style="margin-bottom: 10px">
          <el-col :span="6">
            <el-form-item label="搜索学员:">
              <el-input
                v-model="searchName"
                style="width: 80%"
                placeholder="请输入学员姓名/手机号"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="padding-right: 4%">
            <el-form-item label="结业时间:">
              <el-date-picker
                v-model="cTime"
                type="daterange"
                unlink-panels
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 80%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年级:">
              <el-select
                v-model="gradeName"
                placeholder="请选择年级"
                style="width: 80%"
                clearable
              >
                <el-option
                  v-for="item in gradeList.value"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" icon="Search" @click="toSearch"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="toClear(ruleFormRef)"
              >重置</el-button
            >
          </el-col>
        </el-row>
        <div class="search-collapse" v-show="isCollapse">
          <el-row :gutter="0" style="margin-bottom: 10px">
            <el-col :span="6">
              <el-form-item label="跟进人:">
                <el-select
                  v-model="people"
                  placeholder="请选择跟进人"
                  style="width: 80%"
                  clearable
                >
                  <el-option
                    v-for="item in followPeopleList"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                  >
                    {{ item.nickName }}{{ !item.isJob ? '(已离职)' : '' }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="学管师:">
                <el-select
                  v-model="studyPeople"
                  placeholder="请选择学管师"
                  style="width: 80%"
                  clearable
                >
                  <el-option
                    v-for="item in managerPeopleList"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                  >
                    {{ item.nickName }}{{ !item.isJob ? '(已离职)' : '' }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="最后就读课程:">
                <el-select
                  v-model="lessonName"
                  placeholder="请选择课程"
                  style="width: 80%"
                  clearable
                >
                  <el-option
                    v-for="item in lessonList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0" style="margin-bottom: 10px">
            <!-- <el-col :span="8">
            <span class="search-label"> 标签:</span>
            <el-select
              v-model="classN"
              placeholder="请选择学员来源"
              style="width: 80%"
              @change="toSearch"
            >
              <el-option
                v-for="item in classList.value"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col> -->
            <!-- <el-col :span="8">
              <span class="search-label"> 学员年龄:</span>
              <el-select
                v-model="people"
                placeholder="请选择学员年龄"
                style="width: 80%"
                @change="toSearch"
              >
                <el-option
                  v-for="item in registrarStore.peopleList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                /> </el-select
            ></el-col> -->
          </el-row>
        </div>
      </el-form>
    </div>
    <!-- <div class="manage-students"> -->
    <!-- <el-button type="primary">发消息</el-button> -->
    <!-- <el-button plain @click="openShareDialog('跟进人')">分配跟进人</el-button>
      <el-button plain @click="openShareDialog('学管师')">分配学管师</el-button> -->
    <!-- <el-button plain>导入报读信息</el-button> -->
    <!-- <el-button plain>导出</el-button> -->
    <!-- <el-dropdown placement="bottom-start" style="margin-left: 13px">
        <el-button> 更多操作 </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>群发短信</el-dropdown-item>
            <el-dropdown-item>批量删除</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown> -->
    <!-- </div> -->
    <!-- 表格 -->
    <div class="students-table">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column type="expand" fixed="left">
          <template #default="props">
            <div m="4" style="padding: 0 30px 20px">
              <h3 style="color: rgb(51.2, 126.4, 204)">学员报读情况</h3>
              <el-table :data="props.row.studentCourseList" style="width: 100%" border>
                <el-table-column
                  label="订单号"
                  fixed="left"
                  width="155"
                  show-overflow-tooltip
                  :formatter="formatName"
                >
                  <template #default="scope">
                    <span style="color: #67c23a; cursor: pointer">{{
                      scope.row.orderNo
                    }}</span>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  label="单价"
                  show-overflow-tooltip
                  :formatter="formatName"
                >
                  <template #default="scope">
                    ¥{{ scope.row.originalUnitPrice }}
                  </template>
                </el-table-column> -->
                <el-table-column
                  label="购买项目"
                  show-overflow-tooltip
                  :formatter="formatName"
                  width="150"
                >
                  <template #default="scope">
                    {{ scope.row.courseName }}
                  </template>
                </el-table-column>
                <el-table-column
                  property="addTime"
                  label="创建时间"
                  show-overflow-tooltip
                  :formatter="formatName"
                  width="200"
                />
                <el-table-column
                  label="购买数量"
                  show-overflow-tooltip
                  :formatter="formatName"
                >
                  <template #default="scope">
                    {{ scope.row.countLessonTotalNormal }}课时
                  </template>
                </el-table-column>
                <el-table-column
                  label="赠送数量"
                  show-overflow-tooltip
                  :formatter="formatName"
                >
                  <template #default="scope">
                    {{ scope.row.countLessonTotalGive }}课时
                  </template>
                </el-table-column>
                <el-table-column
                  label="总价"
                  show-overflow-tooltip
                  :formatter="formatName"
                >
                  <template #default="scope">
                    ¥{{ scope.row.courseAmount }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="直减/折扣"
                  show-overflow-tooltip
                  :formatter="formatName"
                >
                  <template #default="scope">
                    ¥ {{ scope.row.courseAmount - scope.row.discountAmount }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="小计"
                  show-overflow-tooltip
                  :formatter="formatName"
                >
                  <template #default="scope">
                    ¥ {{ scope.row.discountAmount }}
                  </template>
                </el-table-column>
                <el-table-column label="剩余" align="center" fixed="right">
                  <el-table-column
                    label="剩余购买数量"
                    show-overflow-tooltip
                    :formatter="formatName"
                  >
                    <template #default="scope">
                      {{ scope.row.remainderLessonNormal }}课时
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="剩余赠送数量"
                    show-overflow-tooltip
                    :formatter="formatName"
                  >
                    <template #default="scope">
                      {{ scope.row.remainderLessonGive }}课时
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="剩余金额"
                    show-overflow-tooltip
                    :formatter="formatName"
                  >
                    <template #default="scope">
                      ¥{{ scope.row.remainderAmount }}
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="学员姓名" fixed="left" width="180">
          <template #default="scope">
            <router-link
              :to="'/registrar/studentsDetails/detail/' + scope.row.id"
              class="link-type"
            >
              <div style="display: flex; align-items: center">
                <span
                  style="margin-right: 10px; color: #67c23a; cursor: pointer"
                  >{{ scope.row.name }}</span
                >
                <el-icon v-if="scope.row.gender == '1'" style="color: #fb6465"
                  ><Female
                /></el-icon>
                <el-icon
                  v-else-if="scope.row.gender == '0'"
                  style="color: #4791ed"
                  ><Male
                /></el-icon>
              </div>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column
          property="mobile"
          label="手机号"
          fixed="left"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column label="年龄" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.ageName ? `${scope.row.ageName}岁` : '-' }}
          </template></el-table-column
        >
        <el-table-column
          property="birthday"
          label="出生日期"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="gradeName"
          label="年级"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="counselor"
          label="跟进人"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="management"
          label="学管师"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="courseName"
          label="最后就读课程"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="addTime"
          label="创建时间"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="turnHistoryDate"
          label="转为历史时间"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />
        <el-table-column
          property="turnHistoryReason"
          label="转为历史原因"
          show-overflow-tooltip
          :formatter="formatName"
          width="130"
        />

        <el-table-column label="操作" width="140" fixed="right">
          <template #default="scope">
            <router-link
              :to="'/registrar/studentsSignUp/index/' + scope.row.id"
              class="link-type"
            >
              <el-button link type="primary">报名</el-button>
            </router-link>

            <el-button link type="primary" @click="toIntention(scope.row)"
              >转为线索</el-button
            >
            <!-- <el-button link type="primary" @click="toLearning(scope.row)"
              >转为在读</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        @pagination="togetStudentsList"
      />
      <div style="height: 10px"></div>
    </div>
    <!-- <ShareDialog
      :isShowShare="isShowShare"
      :shareType="shareType"
      :students="multipleSelection"
      @update:isShowShare="updateShowShare"
      @update:tableList="togetStudentsList"
    /> -->
  </div>
</template>

<script setup>
import Pagination from '@/components/Pagination/index.vue'
// import ShareDialog from '../components/shareDialog/index.vue'
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import useRegistrarStore from '@/store/modules/registrar'
import {
  getStudentsList,
  getLessonList,
  changeIntention,
  changeLearning,
  getManagerList,
  getFollowPeopleList,
  getGradeList,
} from '@/api/studentManagement/index.js'
import GoBack from '@/components/GoBack/index.vue'
const { proxy } = getCurrentInstance()
//获取仓库数据
const registrarStore = useRegistrarStore()
//返回按钮
const route = useRoute()
const title = route.meta.title
//筛选
const searchName = ref('') //学员搜索
const cTime = ref('')
//获取学员来源下拉列表
const searchJoinWay = ref('') //学员来源
const joinWayList = reactive([]) //学员来源列表

//跟进人&学员创建人
const people = ref('') //跟进人
const creatorName = ref('') //学员创建人
const followPeopleList = ref([])
const toFollowPeopleList = async () => {
  try {
    const res = await getFollowPeopleList({ pageNum: 1, pageSize: 9999 })
    if (res.code == 200) {
      followPeopleList.value = res.rows
    }
  } catch (error) {
    console.error('获取学员创建人下拉列表失败:', error)
  }
}
onMounted(toFollowPeopleList)
//学管师
const managerPeopleList = ref([])
const studyPeople = ref('') //学管师
const toGetManagerList = async () => {
  try {
    const res = await getManagerList({ pageNum: 1, pageSize: 9999 })
    if (res.code == 200) {
      managerPeopleList.value = res.data
    }
  } catch (error) {
    console.error('获取学管师下拉列表失败:', error)
  }
}
onMounted(toGetManagerList)

//获取年级下拉列表
const gradeName = ref('')
const gradeList = reactive([]) //所在班级列表
const toGetGradeList = async () => {
  try {
    const res = await getGradeList({})
    if (res.code == 200) {
      gradeList.value = res.data
      registrarStore.setGradeList(gradeList.value)
    }
  } catch (error) {
    console.error('获取年级下拉列表失败:', error)
  }
}
onMounted(toGetGradeList)

//获取课程列表
const lessonName = ref('')
const lessonList = ref([])
const toGetLessonList = async () => {
  try {
    const res = await getLessonList({
      state: 0,
      pageNum: 1,
      pageSize: 9999,
      open:1
    })
    if (res.code == 200) {
      lessonList.value = res.rows
    }
  } catch (error) {
    console.error('获取学生的信息失败:', error)
  }
}
onBeforeMount(toGetLessonList)
//筛选学员列表
function toSearch() {
  togetStudentsList()
}

//控制折叠
const isCollapse = ref(true)
function setCollapse() {
  isCollapse.value = !isCollapse.value
}
//控制分配弹窗
// const isShowShare = ref(false)
// const shareType = ref(1)
// const openShareDialog = (type) => {
//   if (multipleSelection.value.length) {
//     isShowShare.value = true
//     shareType.value = type
//   } else {
//     ElMessage({
//       message: '请选择要分配的学员',
//       type: 'warning',
//     })
//   }
// }
// const updateShowShare = (value) => {
//   isShowShare.value = value
// }

//表格多选操作
// const multipleTableRef = ref()
// const multipleSelection = ref([])
// const handleSelectionChange = (val) => {
//   multipleSelection.value = val
//   console.log('444', multipleSelection.value)
// }
//分页器
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
//处理日期格式
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以加1
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
//获取表格数据
const tableData = ref([])
const togetStudentsList = async () => {
  const params = {
    stage: 5,
    type: 4,
    mine: 0,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    wxParam: searchName.value,
    counselorId: people.value,
    managementId: studyPeople.value,
    gradeId: gradeName.value,
    courseId: lessonName.value,
    gStartTime: cTime.value ? formatDate(cTime.value[0]) : '',
    gEndTime: cTime.value ? formatDate(cTime.value[1]) : '',
  }
  try {
    const res = await getStudentsList(params)
    if (res.code == 200) {
      total.value = res.total
      tableData.value = res.rows
      console.log('55555', tableData.value)
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
  }
}
onMounted(togetStudentsList)
//表格没有数据显示'-'
const formatName = (row, column, cellValue) => {
  return cellValue === '' || cellValue === null ? '-' : cellValue
}
//清空搜索内容
const toClear = () => {
  searchName.value = ''
  people.value = ''
  studyPeople.value = ''
  gradeName.value = ''
  lessonName.value = ''
  cTime.value = ''
  togetStudentsList()
}

//转化在读学员
// const toLearning = (row) => {
//   ElMessageBox.confirm('是否转化为在读学员', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning',
//   })
//     .then(async () => {
//       try {
//         const res = await changeLearning({
//           id: row.id,
//         })
//         if (res.code == 200) {
//           togetStudentsList()
//           ElMessage({
//             type: 'success',
//             message: '转化成功',
//           })
//         } else {
//           ElMessage({
//             type: 'error',
//             message: '转化失败',
//           })
//         }
//       } catch (error) {
//         console.error('转化失败:', error)
//       }
//     })
//     .catch(() => {
//       ElMessage({
//         type: 'info',
//         message: '已取消转化',
//       })
//     })
// }
//转化意向学员
const toIntention = (row) => {
  ElMessageBox.confirm('是否转化为意向学员', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await changeIntention({
          id: row.id,
        })
        if (res.code == 200) {
          togetStudentsList()
          ElMessage({
            type: 'success',
            message: '转化成功',
          })
        } else {
          ElMessage({
            type: 'error',
            message: '转化失败',
          })
        }
      } catch (error) {
        console.error('转化失败:', error)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消转化',
      })
    })
}
</script>

<style lang="scss" scoped>
.current-students {
  .current-students-search {
    position: relative;
    .use-btn {
      position: absolute;
      top: 0;
      right: 0;
      z-index: 100;
      height: 30px;
      cursor: pointer;
    }
    .search-label {
      display: inline-block;
      width: 18%;
      text-align: right;
      margin-right: 8px;
      font-size: 14px;
    }
    .current-students-search-main {
      width: 90%;

      .search-collapse {
        // height: 500px;
        // background-color: red;
      }
    }
  }
  .manage-students {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    height: 40px;
    // background-color: red;
  }
}
</style>